<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
          <!--<el-col :span="6">
            <el-form-item label="合作单位" prop="username">
              <companySelect />
            </el-form-item>
          </el-col> -->
          <el-col :span="10">
            <el-form-item label="" prop="status">
              <el-input
                v-model="queryParams.search"
                placeholder="请输入老师名称,手机号搜索"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="teacher_id" label="ID" width="80" />
        <!-- <el-table-column prop="commercial_insurance_name" label="保险名称" /> -->
        <el-table-column prop="teacher_name" label="老师名称" />
        <el-table-column prop="teacher_phone" label="手机号" />
        <el-table-column prop="graduate_school" label="所属 院校" />
        <el-table-column prop="dealer_name" label="所属经销商" />
        <el-table-column prop="work_experience" label="经验" />
 <el-table-column
        prop="is_banned"
        label="账号状态"
        width="160"
        align="center"
      >
        <template #default="{ row, $index }">
          <el-text type="danger" v-if="row.is_banned == 1">禁用</el-text>
          <el-text type="success" v-if="row.is_banned == 2">启用</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="is_banned" label="状态操作" width="160" align="center">
				<template #default="{row,$index}">
					<el-button type="danger" size="small" v-if="row.is_banned == 2"
						@click="itemBanned(row,1)">禁用</el-button>
					<el-button type="success" size="small" v-if="row.is_banned == 1"
						@click="itemBanned(row,2)">启用</el-button>
				</template>
			</el-table-column>
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button link @click="handleTableOption('edit', scope.row)"
              >编辑</el-button
            >
            <!-- <el-button link type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      title="合作单位"
      width="800"
      :before-close="handleCloseAddDialog"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="150px"
        class="demo-form"
      >
        <!-- 公司ID -->
        <el-form-item label="老师名称" prop="teacher_name">
          <el-input v-model="form.teacher_name" />
        </el-form-item>
        <el-form-item label="头像" prop="teacher_avatar">
          <uploaddom
            :limit="1"
            :imgFile="form.teacher_avatar"
            @change="
              (val) => {
                this.form.teacher_avatar = val;
              }
            "
          />
        </el-form-item>

        <el-form-item label="手机号" prop="teacher_phone">
          <el-input v-model="form.teacher_phone" />
        </el-form-item>
        <el-form-item label="毕业院校" prop="">
          <el-input v-model="form.graduate_school" />
        </el-form-item>
        <el-form-item label="专业" prop="discipline_name">
          <el-input v-model="form.discipline_name" />
        </el-form-item>
        <el-form-item label="经验" prop="work_experience">
          <el-input v-model="form.work_experience" />
        </el-form-item>
        <el-form-item label="标签" prop="tag_data">
          <el-select
            v-model="form.tag_data"
            placeholder="请选择课程标签"
            multiple
            filterable
          >
            <el-option
              v-for="item in tagList"
              :key="item.tag_id"
              :label="item.tag_name"
              :value="item.tag_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教案" prop="course_task_id_str">
           <el-select
            v-model="form.course_task_id_str"
            placeholder="请选择教案"
            filterable
            multiple
          >
            <el-option
              v-for="item in jiaoanList"
              :key="item.course_task_id.toString()"
              :label="item.course_task_title"
              :value="item.course_task_id.toString()"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ dialogType == "edit" ? "修改" : "创建" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";
import companySelect from "@/components/company.vue";
import uploaddom from "@/components/upload.vue";

export default {
  name: "UserList",
  mixins: [tableMixin, ],
  components: { companySelect,uploaddom },
  data() {
    // 结束日期验证
    const validateEndDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择结束日期"));
      }
      if (
        this.form.start_at &&
        new Date(value) < new Date(this.form.start_at)
      ) {
        return callback(new Error("结束日期不能早于开始日期"));
      }
      callback();
    };

    return {
      tagList: [],
      companyChildList: {},
      //查询参数
      queryParams: { search: "" },
      apimodel: "teacher",
      apival: "getList",
      // 状态选项
      statusOptions: [
        { value: -1, label: "全部" },
        { value: 1, label: "生效/上架" },
        { value: 2, label: "不生效/下架" },
        { value: 0, label: "预留" },
      ],
      //创建修改弹窗
      dialogVisible: false,
      dialogType: "",
      jiaoanList:[],
      form: {
        teacher_name: "",
        teacher_avatar: "",
        teacher_phone: "",
        graduate_school: "",
        discipline_name: "",
        work_experience: "",
        tag_data: [],
      },
      rules: {
        teacher_name: [
          { required: true, message: "请输入老师名称", trigger: "change" },
        ],
        teacher_avatar: [
          { required: true, message: "请输入选择头像", trigger: "change" },
        ],
        teacher_phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
        ],
        graduate_school: [
          { required: true, message: "毕业院校", trigger: "change" },
        ],
        discipline_name: [
          { required: true, message: "毕业院校", trigger: "change" },
        ],
        work_experience: [
          { required: true, message: "工作经验", trigger: "change" },
        ],
        tag_data: [
          { required: true, message: "请选择标签", trigger: "change" },
        ],
        course_task_id_str: [
          { required: true, message: "请选择教案", trigger: "change" },
        ],
      },
    };
  },
  mounted(){
    this.getjiaoanList()
    api.tag.getList({ size: 999 ,is_type:2 }).then((res) => {
      if (res.data.code == 200) {
        this.tagList = res.data.content.data;
      }
    });
  },
  methods: {
    
    itemBanned(item, is_banned) {
      this.$request.teacher
        .teacherDeactivate({
          teacher_id: item.teacher_id,
          is_banned,
        })
        .then((res) => {
          if (res && res.data.code == 200) {
                this.getTableData();
          }
        });
    },
    getjiaoanList(){
      api.renwu.getList({size:99999}).then(res=>{
        if(res.data.code == 200){
          this.jiaoanList = res.data.content.data
        }

      })
    },
    openAddDialog(option = "") {
      this.dialogVisible = true;
      this.dialogType = option;
    },

    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        teacher_name: "",
        teacher_avatar: "",
        teacher_phone: "",
        graduate_school: "",
        discipline_name: "",
        work_experience: "",
        tag_data: [],
      };
      this.resetForm();
    },
    // 编辑
    handleTableOption(option, row) {
      if (option == "edit") {
        this.form = {...row};
        this.form.tag_data = []
        if(this.form.course_task_id_str!=''){
        this.form.course_task_id_str = this.form.course_task_id_str.split(",")

        }else{
           this.form.course_task_id_str = []

        }
        console.log('编辑')
        for (let index = 0; index < row.tag_data.length; index++) {
          const element = row.tag_data[index];
          this.form.tag_data.push(element.tag_id)
        }
        this.openAddDialog(option);
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确认删除该合作单位吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.company
            .companyInfoDeleteApi({
              company_id: row.company_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => {});
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 表单验证通过，提交逻辑
          console.log("表单提交:", this.form);
        this.form.course_task_id_str = this.form.course_task_id_str.join(",")
          if (this.dialogType != "edit") {
            api.teacher.create({ ...this.form }).then((res) => {
              if (res?.status == 200) {
                this.$message.success("创建成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          } else {
            api.teacher.update({ ...this.form }).then((res) => {
              if (res?.status == 200) {
                this.$message.success("修改成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          }
          // 这里可以添加API调用等提交逻辑
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
    },
    //选择地点
    handleRegionChange(val) {
      this.form.province_id = val.province;
      this.form.city_id = val.city;
      this.form.area_id = val.district;
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
